package com.yloveg.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.yloveg.base.BaseController;
import com.yloveg.base.ImageToBase64ToImage;
import com.yloveg.base.PictureChangeSize;
import com.yloveg.common.AccessTokenUtil;
import com.yloveg.common.DateUtil;
import com.yloveg.common.PageUtil;
import com.yloveg.common.UrlUtil;
import com.yloveg.common.WeixinUtil;
import com.yloveg.entity.ProductContent;
import com.yloveg.entity.ShopInfo;
import com.yloveg.entity.VActivity;
import com.yloveg.entity.VBusiness;
import com.yloveg.entity.VComplain;
import com.yloveg.entity.VGift;
import com.yloveg.entity.VPlayer;
import com.yloveg.entity.VUser;
import com.yloveg.entity.VVisitLog;
import com.yloveg.entity.VVisitor;
import com.yloveg.service.ProductContentService;
import com.yloveg.service.ShopInfoService;
import com.yloveg.service.VActivityService;
import com.yloveg.service.VBusinessService;
import com.yloveg.service.VComplainService;
import com.yloveg.service.VGiftService;
import com.yloveg.service.VPlayerService;
import com.yloveg.service.VTokenService;
import com.yloveg.service.VUserService;
import com.yloveg.service.VVisitorLogService;

import freemarker.template.utility.StringUtil;

@Controller
@RequestMapping("/free")
public class FreeMainController extends BaseController {
    private final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private ProductContentService productContentService;
    
    @Autowired
    private ShopInfoService shopInfoService;
    
    @Autowired
    private VActivityService vActivityService;
	
	@Autowired
    private VGiftService vGiftService;
	
	@Autowired
    private VPlayerService vPlayerService;
	
	@Autowired
    private VComplainService vComplainService;
	
	@Autowired
    private VTokenService vTokenService;
	
	@Autowired
    private VUserService vUserService;
	
	@Autowired
    private VVisitorLogService vVisitorLogService;
    
	@Autowired
    private VBusinessService vBusinessService;
	
	@Value("#{system.linux_url}")
	private String linux_url;
	@Value("#{system.img_path}")
	private String img_path;
	
    
    @RequestMapping({"{shopId}/index"}) 
    public String index(Integer pageNo,ProductContent product,ModelMap map){
    	String style = "0";
    	if(pageNo==null){
    		pageNo=1;
    	}
    	product.setPublisherState("1");
    	map = PageUtil.freemarkPage(map,productContentService.queryProductContentPage(pageNo,12,product));
    	map.put("productName", product.getProductName());
        //店铺信息
    	ShopInfo info = new ShopInfo();	
    	info.setId(product.getShopId());
    	info = shopInfoService.queryOneShopInfo(info);
    	if(info==null){
    		info = new ShopInfo();	
    	}
    	style = info.getShopStyle();
    	setSessionShop(info);
    	map.put("shopInfo", info);
        return "shopShow/view"+style+"/index";
    }
    
    @RequestMapping({"productDetial"}) 
    public String productDetial(Integer id,ModelMap map){
    	String style = "0";
    	if(id!=null){
        	ProductContent product = productContentService.selectByPrimaryKey(Long.valueOf(id));  
        	map.put("product", product);
        	ShopInfo info = new ShopInfo();
        	map.put("info", info);
        	info.setId(product.getShopId());
        	info = shopInfoService.queryOneShopInfo(info);
        	map.put("shopInfo", info);
        	style = info.getShopStyle();
    	}else{
    		map.put("product", new ProductContent());
    		map.put("shopInfo", new ShopInfo());
    	}
    	
        return "shopShow/view"+style+"/productDetial";
    }
    
    /****************************商业端登录后台日后要移到登录目录*************************************************/
    @RequestMapping({"my"}) 
    public String my(ModelMap map){
    	
    	return "landing/mobile/personalCenter/my";
    }
    
    @RequestMapping("/playerList") 
    public String playerList(ModelMap map,int activityid){
    	VActivity activity=vActivityService.selectByPrimaryKeyN(activityid);
    	if("N".equals(activity.getSts())) {
    		return "free/actclose";
    	}
    	map.put("activityid", activityid);
    	return "free/playerList";
    }
    
    //授权地址获取
    @RequestMapping("/getAuthorizeUrl") 
    @ResponseBody
    public JSONObject getAuthorizeUrl(int activityid) {
    	JSONObject josn = new JSONObject();
    	String url = WeixinUtil.getAuthorizeUrl(activityid);
    	josn.put("authorizeUrl", url);
    	return josn;
    }
    
    //获取openid
    @RequestMapping("/getOpenid") 
    @ResponseBody
    public JSONObject getOpenid(String code) {
    	JSONObject returnJson = new JSONObject();
    	JSONObject json = WeixinUtil.getAccess_token(code);
    	//1.根据code获取openid
    	String openid=null;
    	String access_token=null;
    	if(json.containsKey("openid")) {
    		openid=json.getString("openid");
    		access_token=json.getString("access_token");
    		returnJson.put("code", 1);
    		returnJson.put("msg", "success");
    		returnJson.put("openid", openid);
    		returnJson.put("access_token", access_token);
    		return returnJson;
    	}else {
    		returnJson.put("code", 0);
    		returnJson.put("msg", "无效的code");
    		return returnJson;
    	}
    }
    
    @RequestMapping("/getUserInfo") 
    @ResponseBody
    public JSONObject getUserInfo(String openid , String access_token) {
    	JSONObject returnJson = new JSONObject();
    	//根据openid查询用户表。若没记录，则调用微信接口，获取用户信息，并同步到用户表。
    	VUser user=new VUser();
    	List<VUser> vuser=vUserService.selectByOpenid(openid);
    	if(vuser!=null && vuser.size()==0) {
    		user.setOpenid(openid);
    		user.setNickname(openid);
    		vUserService.insertVUser(user);
    		returnJson.put("code", 1);
    		returnJson.put("msg", "success");
    		returnJson.put("userinfo", user);
    		return returnJson;
    	}else {
    		user=vuser.get(0);
    		returnJson.put("code", 1);
    		returnJson.put("msg", "success"); 
        	returnJson.put("userinfo", user);
        	return returnJson;
    	}	
    }
    
    //即时访问用户信息保存
    @RequestMapping("/saveNowUserMsg") 
    @ResponseBody
    public void saveNowUserMsg(int activityid,String openid) {
    	//1.先判断该用户今天有没有访问
    	VVisitLog vVisitLog= new VVisitLog();
    	vVisitLog.setActivityid(activityid);
    	vVisitLog.setOpenid(openid);
    	List<VVisitLog> visitList = vVisitorLogService.selectByOpenidAndActidAndTime(vVisitLog);
    	//2.证明该用户今天是第一次访问
    	if(visitList!=null && visitList.size()==0) {
    		vVisitorLogService.insertVVisitorLog(vVisitLog);
    	}
    	VActivity activity=vActivityService.selectByPrimaryKeyN(activityid);
    	VActivity activityN = new VActivity();
    	if(activity!=null) {
    		activityN.setId(activity.getId());
    		activityN.setTotalnum(activity.getTotalnum()+1);
    		activityN.setDaynum(activity.getDaynum()+1);
        	vActivityService.updateByPrimaryKeySelective(activityN);	
    	}
    }
    
    //用户投诉
    @RequestMapping("/complaint") 
    public String toComplain(ModelMap map,int activityid) {
    	map.put("activityid", activityid);
    	return "free/complaint";
    }
    
    @RequestMapping("/saveComplain") 
    @ResponseBody
    public Map<String, Object> saveComplain(Integer activityid,String type,String content) {
    	VComplain vComplain = new VComplain();
    	vComplain.setActivityid(activityid);
    	vComplain.setType(type);
    	vComplain.setContent(content);
    	Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		result = vComplainService.insertComplain(vComplain);
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;		
    }
    
    @RequestMapping("/getWeinxinDate") 
    @ResponseBody
    public Map<String, Object> returnWeixinDate(int activityid ,int pageNo) {
    	JSONObject json  = vPlayerService.returnWeixinDate(activityid);
    	return json;
    }
    
    @RequestMapping("/getPlayInfo") 
    @ResponseBody
    public Map<String, Object> getPlayInfo(int activityid ,int pageNo ,String title){
    	JSONObject json = new JSONObject(); 
    	//选手信息
    	PageInfo<VPlayer> list= vPlayerService.queryActivityPageByactivityIsYN(pageNo,10,activityid,title);
    	Map<String, Object> map = PageUtil.dateToLayTable(list);
    	json.put("playlist", map);
    	return json;
    }
    
    //我要报名
    @RequestMapping("/toEnroll") 
    public String toEnroll(ModelMap map,int activityid) {
    	map.put("activityid", activityid);
    	return "free/enroll";
    }
    
    //活动介绍
    @RequestMapping("/toActivityIntr") 
    public String toActivityIntr(ModelMap map,int activityid) {
    	map.put("activityid", activityid);
    	return "free/ActivityInto";
    }
    
    @RequestMapping("/getActivityIntr") 
    @ResponseBody
    public Map<String, Object> getActivityIntr(int activityid) {
    	JSONObject json = new JSONObject(); 
    	VActivity activity=vActivityService.selectByPrimaryKeyN(activityid);
    	json.put("activityintr", activity.getActivitpic());
    	return json;
    }
    
    //选手详情页
    @RequestMapping("/toPlayerDetail") 
    public String toPlayerDetail(ModelMap map,int playerid){
    	map.put("playerid", playerid);
    	return "free/detail";
    }
    
    
    @RequestMapping("/getPlayerDetail") 
    @ResponseBody
    public Map<String, Object> getPlayerDetail(int playerid) {
    	return vPlayerService.getPlayerDetail(playerid);
    }
    
    //用户点赞
    @RequestMapping("/userThumb") 
    @ResponseBody
  	public JSONObject userThumb(int activityid,int playerid,String openid) {
    	JSONObject json = new JSONObject(); 
    	VActivity activity=vActivityService.selectByPrimaryKeyN(activityid);
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	Date enddate = null;
    	Date startdate = null;
    	try {
    		enddate = sdf.parse(activity.getEndTime());
    		startdate = sdf.parse(activity.getStartTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	if(enddate.before(new Date())) {
    		json.put("code", "0004");
    		json.put("msg", "活动已结束");
    	}else {
    		if(startdate.after(new Date())) {
    			json.put("code", "0005");
        		json.put("msg", "活动未开始");
    		}else {
    			VBusiness vBusiness = new VBusiness();
            	vBusiness.setActivityid(activityid);
            	vBusiness.setPlayerid(playerid);
            	vBusiness.setOpenid(openid);
            	//1.判断当前用户当前活动是否点赞超过5次
            	List<VBusiness> list1= vBusinessService.selectByActidAndTime(vBusiness);
            	if(list1!=null && list1.size()>=5) {
            		json.put("code", "0001");
            		json.put("msg", "该活动今日点赞次数已达上限");
            	}else {
            		//2.判断该活动，该用户是否给该选手点过赞
            		List<VBusiness> list2= vBusinessService.selectByActidAndPlayerAndTime(vBusiness);
            		if(list2!=null && list2.size()>0) {
            			json.put("code", "0002");
                		json.put("msg", "今日已给该选手点赞");
            		}else {
            			//3.用户点赞
            			VPlayer vp = vPlayerService.selectByPrimaryKey(playerid);
            			if("D".equals(vp.getSts())) {
            				json.put("code", "0006");
                    		json.put("msg", "你涉嫌刷票，点赞失败！");
            			}else {
            				vp.setPoll(vp.getPoll()+1);
                			vPlayerService.updateByPrimaryKeySelective(vp);
                			vBusiness.setBusniessType("1");
                			vBusinessService.insertVBusiness(vBusiness);
                			VActivity vActivityN = new VActivity();
                			vActivityN.setId(activity.getId());
                			vActivityN.setThumbnum(activity.getThumbnum()+1);
                			vActivityService.updateByPrimaryKeySelective(vActivityN);
                			json.put("code", "0003");
                    		json.put("msg", "点赞成功");
            			}
            		}
            	}
    		}
    	}
    	return json;
  	}
    
    //用户赠送礼物页面跳转
    @RequestMapping("/toUserSendGift") 
  	public String toUserSendGift(ModelMap map,int activityid,int playerid,String openid) {
    	VActivity activity=vActivityService.selectByPrimaryKeyN(activityid);
    	String giftid=activity.getGift();
    	String [] gid = giftid.split(",");
    	List<VGift> vglist= new ArrayList<VGift>();
    	for(int i=0;i<gid.length;i++) {
    		VGift vg = vGiftService.selectByPrimaryKey(Integer.parseInt(gid[i]));
    		vglist.add(vg);
    	}
    	map.put("vglist", vglist);
    	map.put("activityid", activityid);
    	map.put("openid", openid);
    	map.put("playerid", playerid);
    	return "free/sendGift";
  	}
    
    //奖品跳转
    @RequestMapping("/toGift") 
    public String toGift(ModelMap map,int activityid) {
    	map.put("activityid", activityid);
    	return "free/gift";
    }
    
    @RequestMapping("/getGift") 
    @ResponseBody
    public Map<String, Object> getGift(int activityid) {
    	JSONObject json = new JSONObject(); 
    	VActivity activity=vActivityService.selectByPrimaryKeyN(activityid);
    	json.put("giftlist", activity.getPrizepic());
    	return json;
    }
    
    //获取选手排行榜
    @RequestMapping("/toRankList") 
    public String toRankList(ModelMap map,int activityid) {
    	map.put("activityid", activityid);
    	return "free/rankList";
    }
    
    @RequestMapping("/getRankList") 
    @ResponseBody
    public Map<String, Object> getRankList(int activityid){
         return vPlayerService.getRankList(activityid);
    }
    
    //新增选手报名
	@RequestMapping("/saveOrUpdatePlayer")
	@ResponseBody
	public Map<String, Object> saveOrUpdatePlayer(VPlayer vPlayer){
		Map<String, Object> map = new HashedMap<String, Object>();
		int result = 0;
		String url = "0";
		if(vPlayer.getId()==0) {
			/*
			 * try { while("0".equals(url)){ url =
			 * PictureChangeSize.getImg(vPlayer.getPlayerpicbig(), img_path, linux_url,4); }
			 * vPlayer.setPlayerpic(url); url = "0"; while("0".equals(url)){ url =
			 * PictureChangeSize.getImg(vPlayer.getPlayerpicbig(), img_path, linux_url,3); }
			 * vPlayer.setPlayerpcim(url); url = "0"; } catch (IOException e) {
			 * e.printStackTrace(); }
			 */
			vPlayer.setPlayerpic(ImageToBase64ToImage.Base64ToImage(vPlayer.getPlayerpic(),img_path, linux_url));
			vPlayer.setPlayerpicbig(ImageToBase64ToImage.Base64ToImage(vPlayer.getPlayerpicbig(),img_path, linux_url));
			vPlayer.setPlayerno(vPlayerService.queryVPlayerNO(vPlayer)+1);
			vPlayer.setAmount(0.00);
			vPlayer.setPoll(0);
			result = vPlayerService.insertPlayer(vPlayer);
			if(result>0) {
				VActivity activity=vActivityService.selectByPrimaryKeyN(vPlayer.getActivityid());
				VActivity activityNew = new VActivity();
				activityNew.setPalyernum(activity.getPalyernum()+1);
				activityNew.setId(activity.getId());
				vActivityService.updateByPrimaryKeySelective(activityNew);
			}
		}else {
			/*
			 * try { while("0".equals(url)){ url =
			 * PictureChangeSize.getImg(vPlayer.getPlayerpicbig(),img_path,linux_url,4); }
			 * vPlayer.setPlayerpic(url); while("0".equals(url)){ url =
			 * PictureChangeSize.getImg(vPlayer.getPlayerpicbig(), img_path, linux_url,3); }
			 * vPlayer.setPlayerpcim(url); url = "0"; } catch (IOException e) {
			 * e.printStackTrace(); }
			 */
			result = vPlayerService.updateByPrimaryKeySelective(vPlayer);
		}
   
		if(result>0){
			map.put("code", "1");
			map.put("msg", "操作成功！");
		}else {
			map.put("code", "0");
			map.put("msg", "系统错误请联系管理员！");
		}
		return map;		
	}
	
	//获取分享接口参数
    @RequestMapping("/getSharePram")
	@ResponseBody
	public Map getSharePram(String url) {
		Map map=WeixinUtil.getSharePram(vTokenService.selectNew() , url);
    	//Map map=WeixinUtil.getSharePram(AccessTokenUtil.getAccessTockenResult() , url);
		return map;
	}
    
}
